<?php
namespace app\admin\controller;

use app\common\model\Enroll as EnrollModel;
use app\common\model\Style as StyleModel;
use app\common\model\Exhibition as ExhibitionModel;
use app\admin\tool\Parser;
use app\common\model\Admin as AdminModel;
use app\common\model\DistributeUserLog;
use app\common\model\DistributeUser;
use app\common\model\Users;
use think\Request;
use think\Db;

class Enroll extends  Base{

    /**
     * 风格列表 给column调用
     * @var array
     */
    protected $style_list = [];

    /**
     * 活动列表 给column调用
     * @var array
     */
    protected $exhibition_list = [];

    /**
     * 用户报名列表
     */
    public function index(Request $request){

        $mobile    = $request->get('mobile','');
        $real_name = $request->get('real_name','');
        $where = [];
        if(!empty($mobile)) $where['mobile'] = ['like','%'.$mobile.'%'];
        if(!empty($real_name)) $where['real_name'] = ['like','%'.$real_name.'%'];

        $model = EnrollModel::where($where)->order('add_time desc')->paginate(10);

        //报名的活动 和 风格查询
        $exhibition_list = [];
        $style_list = [];
        foreach($model as $key => $item){
            array_push($exhibition_list,$item['exhibition_id']);
            $styles = explode(',',$item['style_ids']);
            $style_list = array_merge($style_list,$styles);
        }
        $style_list = array_unique($style_list);
        $exhibition_list = array_unique($exhibition_list);

        $this->style_list = StyleModel::where('id','in',$style_list)->column('title','id');
        $this->exhibition_list = ExhibitionModel::where('id','in',$exhibition_list)->column('title','id');

        $parser = new Parser();

        $this->data['title']  = '报名列表';
        $this->data['column'] = $this->column();
        $this->data['model']  = $model;
        $this->data['parser'] = $parser;
        $this->data['query']  = ['mobile'=>$mobile,'real_name'=>$real_name];

        return view('',$this->data);

    }


    /**
     * 查看报名详情
     * @param Request $request
     * @throws
     * @return template
     */
    public function show(Request $request){
        $id = $request->param('id');
        $enroll = EnrollModel::get($id);

        $this->data['title'] = '报名详情';
        $this->data['model'] = $enroll;

        //活动 与  风格
        $exhibition = ExhibitionModel::where('id',$enroll->exhibition_id)->column('title');

        if($exhibition){
            $enroll->exhibition_name = $exhibition[0];
        }
        $style_ids = explode(',',$enroll->style_ids);
        $enroll->styles = '';
        if($style_ids){
            $styles = StyleModel::where("id",'in',$style_ids)->column('title');
            $styles = implode(',',$styles);
            $enroll->styles = $styles;
        }

        $this->data['exhibition'] = $exhibition;

        return view('',$this->data);
    }


    /**
     * 修改报名 这个需要具有一定权限的人才能修改 而且要对修改行为做记录
     * @param Request $request
     */
    public function edit(Request $request){
        $id = $request->param('id');
        $this->error("没有权限修改");
    }



    /**
     * 分配报名用户给后台用户、
     * 每次报名都要分配 所以同一个用户在不同的活动中可以分配给不同的人 但是分配之后 前面的分配关系就会解除
     * @param Request $request
     * @return \think\response\View
     * @throws
     */
    public function distributeUser(Request $request){
        $platform_user_id  = $request -> param('id');
        $platform_user = AdminModel::get($platform_user_id);
        $model = DistributeUser::where(['admin_id'=>$platform_user_id,'state'=>0])->paginate(10);
        $user_list = [];
        foreach( $model as $key => $item ){
            array_push($user_list,$item['user_id']);
        }

        $exhibition = ExhibitionModel::where('exhibition_time','>',time())->where('state',0)->order('exhibition_time desc')->find();
        $user_list= EnrollModel::where('user_id','in',$user_list)->where('exhibition_id',$exhibition['id'])->column('real_name,mobile,province_name,city_name,district_name,user_id','id');


        $this->data['title']  = $platform_user->nickname. ' 的客户';
        $this->data['column'] = [
            'real_name'=>['name'=>'用户姓名','fun'=>'text','options'=>''],
            'mobile'=>['name'=>'用户手机号码','fun'=>'text','options'=>''],
            'province_name'=>['name'=>'省','fun'=>'text','options'=>''],
            'city_name'=>['name'=>'市','fun'=>'text','options'=>''],
            'district_name'=>['name'=>'区','fun'=>'text','options'=>''],
        ];
        $this->data['parser'] = new Parser();
        $this->data['model']  = $user_list;
        $this->data['p_user_id'] = $platform_user_id;

        return view('',$this->data);

    }

    /**
     * 具体报名参加活动的用户
     * 目前 以最新的活动 且 未结束的活动为准
     */
    public function users(){
        //最新正在进行的活动
        $exhibition = ExhibitionModel::where('exhibition_time','>',time())->where('state',0)->order('exhibition_time desc')->find();
        $parser = new Parser();
        if($exhibition){
            //从这场活动寻找报名的人
            $users = EnrollModel::where(['exhibition_id'=>$exhibition['id']])->order('id desc')->paginate(10);
            $this->data['model'] = $users;
            $this->data['title'] = "用户列表";
            $this->data['column'] = [
                'real_name'=>['name'=>'姓名','fun'=>'text','options'=>''],
                'province_name'=>['name'=>'省','fun'=>'text','options'=>''],
                'city_name'=>['name'=>'市','fun'=>'text','options'=>''],
                'district_name'=>['name'=>'区','fun'=>'text','options'=>''],
                'mobile'=>['name'=>'手机','fun'=>'text','options'=>''],
                'add_time'=>['name'=>'报名时间','fun'=>'datetime','options'=>[]],
            ];
            $this->data['parser'] = $parser;
        }else{
            $this->data['model'] = [];
            $this->data['title'] = "没有正在进行的活动";
            $this->data['parser'] = $parser;
        }

        return view('',$this->data);
    }

    /**
     * 关联前后台用户
     * @param Request $request
     * @throws
     */
    public function makeRelation(Request $request){

        $user_id = $request->param('user_id');
        //平台用户id
        $platform_user_id = $request->param('p_user_id');


        //后台检测用户的合法性 不能随便前台关联
        $exhibition = ExhibitionModel::where('exhibition_time','>',time())->where('state',0)->order('exhibition_time desc')->find();
        if(!$exhibition){
            $this->error("当前不能进行改操作，没有团购活动");
        }

        //检查该用户是否报名
        $res = EnrollModel::where(['user_id'=>$user_id,'exhibition_id'=>$exhibition['id']])->find();
        if( !$res ){
            $this->error("关联失败");
        }

        //检查该后台用户是否具有权限
        $platform_user = AdminModel::get($platform_user_id);
        if(!$platform_user->hasPermission('admin/enroll/makeralation/tiny')){
            $this->error('关联的后台用户不具有该权限');
        }

        $data = [];
        $data['admin_id'] = $platform_user_id;
        $data['user_id'] = $user_id;
        $data['add_time'] = time();
        $data['exhibition_id'] = $exhibition['id'];
        $data['op_type'] = 1;
        $data['op_user'] = $this->admin->id;

        //关联
        Db::transaction(function () use ($data,$platform_user) {
            $relation = DistributeUser::where(['user_id'=>$data['user_id'],'role'=>$platform_user->role])->find();
            if($relation){
                if($relation['admin_id'] == $data['admin_id'] && $relation['state'] == 0){
                    $this->success("操作成功");
                }
                //跟一个用户产生关联后，跟另外一个关联的关联删除 办法是直接更新admin_id
                DistributeUser::update(['admin_id'=>$data['admin_id'],'state'=>0],['user_id'=>$data['user_id'],'role'=>$platform_user->role]);
            }else{
                DistributeUserLog::create($data);
                DistributeUser::create(['admin_id'=>$data['admin_id'],'user_id'=>$data['user_id'],'role'=>$platform_user->role]);
            }
        });


        $this->success("操作成功");
    }



    /**
     * 移除关系
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function removeRelation(Request $request){
        $user_id = $request->param('user_id');
        $platform_user_id = $request->param('p_user_id');

        $platform_user = AdminModel::get($platform_user_id);

        $distribute_user = DistributeUser::where(['state'=>0,'admin_id'=>$platform_user_id,'user_id'=>$user_id,'role'=>$platform_user->role])->find();
        if(!$distribute_user){
            $this->success("删除成功");
        }


        Db::transaction(function() use ($user_id,$platform_user_id,$platform_user){
            DistributeUser::update(['state'=>'1'],['admin_id'=>$platform_user_id,'user_id'=>$user_id,'role'=>$platform_user->role]);

            $data = [];
            $data['admin_id'] = $platform_user_id;
            $data['user_id'] = $user_id;
            $data['add_time'] = time();
            $data['exhibition_id'] = 0; //删除操作不记录哪次活动，因为有可能没有活动
            $data['op_type'] = 2; //类型 删除
            $data['op_user'] = $this->admin->id;

            DistributeUserLog::create($data);
        });

        $this->success('删除成功');
    }



    protected function column(){
        return [
            'real_name'=>['name'=>'姓名','fun'=>'text','options'=>''],
            'province_name'=>['name'=>'省','fun'=>'text','options'=>''],
            'city_name'=>['name'=>'市','fun'=>'text','options'=>''],
            'district_name'=>['name'=>'区','fun'=>'text','options'=>''],
            'mobile'=>['name'=>'手机','fun'=>'text','options'=>''],
            'exhibition_id'=>['name'=>'报名活动','fun'=>'translate','options'=>['map'=>$this->exhibition_list]],
            'style_ids'=>['name'=>'风格','fun'=>'translateMulti','options'=>['map'=>$this->style_list]],
            'invite_code'=>['name'=>'邀请码','fun'=>'text','options'=>''],
            'add_time'=>['name'=>'报名时间','fun'=>'datetime','options'=>[]],
        ];
    }




}